<template>
  <div class="allCustomersManagement" id="allCustomersZ">
    <div class="newArticleStyle">
      <div class="topList">
        <customTopListVue
          ref="customTopList"
          :fromType="'allCustomer'"
          :topRocerdData="topRocerdData"
          @getClickData="getClickData" />
      </div>
      <div class="imprt" style="margin-top: 10px">
        <!-- <Checkbox v-model="careFlag" @on-change="careStatusChange"> 只看我关注的</Checkbox> -->
        <Poptip trigger="hover">
          <Button type="primary" v-if="unlocking('0101010700')">导出</Button>
          <div slot="content">
            <div class="impotBtn" @click="exportExcelFun(2, '1')">导出全部字段</div>
            <div class="impotBtn" @click="exportExcelFun(1, '1')">导出台账字段</div>
          </div>
        </Poptip>
        <Poptip trigger="hover">
          <Button type="primary" v-if="unlocking('0101010100')">导出Excel</Button>
          <div slot="content">
            <div class="impotBtn" @click="exportExcelFun(2, '0')">导出全部字段</div>
            <div class="impotBtn" @click="exportExcelFun(1, '0')">导出台账字段</div>
          </div>
        </Poptip>
        <Button type="primary" @click="assignCustomers" v-if="unlocking('0101010200')">分配客户</Button>
        <Button type="primary" @click="adjustHeader" v-if="unlocking('0101010300')">调整表头排序</Button>
        <Button type="primary" @click="goStandBookList" v-if="unlocking('0101010400')">编辑本案台账</Button>
        <Button type="primary" @click="importAccount" v-if="unlocking('0101010500')">导入台账</Button>
        <Button type="primary" class="operation" v-if="unlocking('0101010900')" @click="operationClick">
          查看导出记录
        </Button>
        <Button type="primary">
          <a
            href="https://images.tospurfang.com/doc/%E5%AE%A2%E6%88%B7%E7%AE%A1%E7%90%86%E6%93%8D%E4%BD%9C%E8%AF%B4%E6%98%8E.pdf"
            style="color: #fff"
            target="_blank">
            查看操作指引
          </a>
        </Button>
      </div>
    </div>
    <Spin fix v-show="loading">
      <Icon type="ios-loading" size="20" class="dt-loading"></Icon>
      <div>Loading</div>
    </Spin>
    <dt-grid
      ref="allCustomer"
      :scrollDefault="false"
      :columns="columns"
      :cell-height="80"
      page
      :onFetch="onFetch"></dt-grid>
    <dynamic-header
      ref="dynamicHeader"
      @fieldCancel="fieldCancel"
      @headUpdate="headUpdate"
      :sourcedata="sourcedata"
      :targetdata="targetdata"></dynamic-header>
    <Modal
      v-model="importFlag"
      title="台账导入"
      :footer-hide="true"
      width="800"
      @on-cancel="importAccountCancel">
      <Table :columns="importColumns" :data="importData" max-height="400"></Table>

      <div class="transferFooter">
        <Button @click="importAccountCancel">取消</Button>
        <Upload
          :disabled="importStatusFlag"
          :action="upload.reqUrl"
          :format="['xlsx', 'xls', 'XLS', 'XLSX']"
          ref="upload"
          :data="upload.data"
          name="excelFile"
          :headers="upload.headers"
          :on-format-error="handleFormatError"
          :before-upload="handleBefore"
          :on-error="handleError"
          :on-progress="handleProgress"
          :show-upload-list="false">
          <Tooltip
            placement="top"
            max-width="200"
            content="当前已有正在执行的导入任务，请稍后再试"
            :disabled="!importStatusFlag">
            <Button type="primary" :disabled="importStatusFlag">导入台账</Button>
          </Tooltip>
        </Upload>
      </div>
    </Modal>

    <Modal v-model="detailsFlag" title="客户详情" width="80%" :styles="{ top: '5%' }" :footer-hide="true">
      <div class="detailsCon">
        <detail-page v-if="detailsFlag" :detailsParams="detailsParams" @change="onDetailChange"></detail-page>
      </div>
    </Modal>
    <preview-image :images="preViewImg" :showIndex="showIndex" ref="preViewImage"></preview-image>
    <operation-record ref="operationRecord"></operation-record>
  </div>
</template>
<script>
  import customerMgr from '@/biz/customer/customer'
  import dynamicHeader from '@/components/dynamicHeader.vue'
  import poptipContent from './components/poptipContent'
  import detailPage from './details'
  import columnConfig from './opt/customerColumn'
  import userMgr from '@/biz/user'
  import toolApi from '@/biz/base/tool'
  import customerOptMgr from '@/biz/customer/customerOpt.js'
  import customTopListVue from '@/components/customTopList.vue'
  import clueCustomerMgr from '@/biz/customer/clueCustomer.js'
  export default {
    components: {
      poptipContent,
      detailPage,
      dynamicHeader,
      customTopListVue
    },
    data() {
      return {
        clickKey: '',
        topRocerdData: {},
        queryType: null,
        showIndex: 0,
        preViewImg: [],
        hasAttention: null,
        careFlag: false, //关注的
        detailsParams: {},
        detailsFlag: false,
        popLoading: true,
        importStatusFlag: false,
        importStatusFlag1: false,
        exportParams: {},

        popClass: '',
        popLen: 0,
        importFlag: false,
        importData: [],
        importColumns: columnConfig.importColumns(),
        //跟进记录
        followUpList: [],
        sourcedata: [],
        targetdata: [],
        buildingId: this.$dt.buildInfo().housesId,
        buildMess: this.$dt.buildInfo(), //案场的所有信息
        upload: customerMgr.importParameterExcel({
          userId: userMgr.info().userId
        }),
        appId: userMgr.info().appId,
        nameCrimeSceneList: [],
        roleName: userMgr.info().role.roleName,
        loading: false,
        columns: [],
        columns2: columnConfig.columns2,
        pageData1: {
          total: 0,
          current: 1,
          rows: 10,
          pageSizeOpts: [50, 40, 30, 20, 10]
        },
        userMess: userMgr.info()
      }
    },
    methods: {
      // 点击上方列表传过来的值
      getClickData(val) {
        console.log('子组件传过来的值', val)
        this.queryType = val.queryType
        this.clickKey = val.queryType ? val.key : ''
        this.$refs.allCustomer.fetch()
      },
      operationClick() {
        this.$refs.operationRecord.show('export_visitCustomer', 'M_4', this.$dt.buildInfo().housesId)
      },
      lookImg(val) {
        this.preViewImg = val
        this.$refs.preViewImage.show()
      },
      onDetailChange() {
        this.initData()
      },
      careStatusChange(val) {
        if (val) {
          this.hasAttention = 1
        } else {
          this.hasAttention = null
        }
        this.initData(true)
      },
      // 更新跟进记录
      getUpdateFollowUp(val) {
        let params = {
          userCustomerId: val.userCustomerId,
          customerId: val.customerId,
          operatorId: this.userMess.userId,
          buildingId: this.buildingId,
          category: '4'
        }
        customerMgr.updateFollowUp(params).then((res) => {
          if (String(res) == 'true') {
            val.newNews = 2
          }
        })
      },

      //查询跟进记录
      getFollowUp(val) {
        this.popLoading = true
        this.popClass = ''
        this.followUpList = []
        this.popLen = 0
        let params = {
          page: this.pageData1.current,
          rows: this.pageData1.rows,
          userCustomerId: val.userCustomerId,
          category: '4,12',
          buildingId: this.buildingId,
          customerId: val.customerId,
          operatorId: this.userMess.userId
        }
        customerMgr.followUp(params).then((res) => {
          this.followUpList = res.records
          this.popLen = res.total
          this.getUpdateFollowUp(val)
          this.popLoading = false
        })
      },
      // 导入格式判断
      handleFormatError(file) {
        this.$Message.error('只支持上传Excel表格！')
      },
      // 导入中
      handleProgress() {
        this.importFlag = false
        this.$Message.info('导入中。')
        // this.importAccount()
      },
      // 导入前
      handleBefore() {
        let statusFlag = this.importData.some((item) => {
          return item.status == 0
        })
        if (statusFlag) {
          this.$Message.info('当前已有正在执行的导入任务，请稍后再试。')
          return false
        } else {
          return true
        }
      },
      importAccountCancel() {
        this.importFlag = false
      },
      importAccount() {
        this.importFlag = true
        let params = {
          userId: this.userMess.userId
        }
        customerMgr.importCustomerList(params).then((res) => {
          this.importData = res
          let statusFlag = this.importData.some((item) => {
            return item.status == 0
          })
          if (statusFlag) {
            this.importStatusFlag = true
            this.importStatusFlag1 = false
          } else {
            this.importStatusFlag = false
            this.importStatusFlag1 = true
          }
        })
      },
      goStandBookList() {
        this.$router.push({
          name: 'buildingConfigure',
          params: {
            fromCustomer: 'buildingFileld'
          }
        })
      },
      adjustHeader() {
        this.$refs.dynamicHeader.show()
      },
      fieldCancel() {
        this.$refs.dynamicHeader.hide()
      },
      headUpdate(params) {
        customerMgr.customerHeadUpdate(params).then((res) => {
          this.getCustomerHeadList()
          this.$refs.allCustomer.clearFilter()
          this.$refs.allCustomer.fetch(true)
          this.$nextTick(function () {
            this.$refs.dynamicHeader.hide()
          })
        })
      },
      //获取表头
      getCustomerHeadList() {
        return customerOptMgr.columns().then((res) => {
          console.log(res, '表头')
          if (res) {
            this.columns = columnConfig.options(this, res.resArr)
            this.sourcedata = res.hiedHead
            this.targetdata = res.showHead
          }
        })
      },
      importDownload(id) {
        let params = {
          id: id,
          fileName: '客户导入明细.xls'
        }
        customerMgr.exportParameterExcel(params)
      },
      handleError(val) {
        this.$Message.error(val.msg)
      },
      getChangeAttention(val) {
        let params = {
          buildingId: val.buildingId,
          roleId: userMgr.info().role.roleId,
          userCustomerId: val.userCustomerId,
          userId: this.userMess.userId
        }
        customerMgr.changeAttention(params).then((res) => {
          this.$Message.success(res == 1 ? '成功收藏该客户。' : '你取消收藏了该客户。')
          this.initData()
        })
      },
      // 获取顶部count数据
      getCountData(data) {
        let params = {
          ...data,
          buildingId: this.buildingId //楼盘id
        }
        customerMgr.customerCount(params).then((res) => {
          this.topRocerdData = res

          //判断案场保护期是否开启 若案场保护期未开启，则过期客户、即将过期客户不展示
          //即将过期客户
          let willExpiredIndex = this.$refs.customTopList.topRocerd.allCustomer.findIndex(
            (ele) => ele.key == 'overdueCustomer'
          )
          this.$refs.customTopList.topRocerd.allCustomer[willExpiredIndex].hideItem =
            res.protectConfig == 0 ? true : false
          //过期客户
          let expiredIndex = this.$refs.customTopList.topRocerd.allCustomer.findIndex(
            (ele) => ele.key == 'soonOverdueCustomer'
          )
          this.$refs.customTopList.topRocerd.allCustomer[expiredIndex].hideItem =
            res.protectConfig == 0 ? true : false
          this.$refs.customTopList.handleArrow()
        })
      },
      onFetch(data) {
        let params = {
          roleId: userMgr.info().role.roleId,
          userId: this.userMess.userId,
          hasAttention: this.hasAttention,
          // queryType: this.queryType,
          buildingId: this.buildingId, //楼盘id
          // userCustomerId: this.$route.params.customerListFormStatistics || [], //首页统计面板过来, //用户客户ID
          ...data
        }
        if (this.$route.params.customerListFormStatistics) {
          params.userCustomerId = this.$route.params.customerListFormStatistics
        }
        console.log(params, 'ppp')
        this.getCountData(params)
        params.queryType = this.queryType
        this.exportParams = params
        this.$dt.stats.customerFilter(params)
        console.log('this is params', params)
        return customerMgr.getCustomerListNew(params).then((res) => {
          console.log('这是一个客户列表', res)
          res.records &&
            res.records.forEach((item) => {
              if (item.featurePhoto) {
                item.featurePhoto = item.featurePhoto.split(',')
              } else {
                item.featurePhoto = []
              }
            })
          res.list = res.records
          this.list = res.records
          return res
        })
      },
      // 导出Excel
      exportExcelFun(val, mask) {
        var params = {
          dto: this.exportParams,
          maskCustomerPhone: mask
        }
        params.dto.page = 1
        params.dto.rows = 9999
        if (val == 1) {
          params.type = 1
        } else {
          params.type = 2
        }
        toolApi.downloadCenter('/dt-customer/customerList/webList/export', params)
      },
      assignCustomers() {
        // this.$router.push({
        //   path: '/allCustomersManagement/allCustomers/assignCustomers',
        // })
        this.$router.push({
          path: '/allCustomersManagement/visitAssign',
          query: {
            fromPage: 'allCustomer',
            fromKey: this.clickKey
          }
        })
      },

      // 查看详情
      viewClick(rows, isFollow) {
        if (isFollow) {
          this.$dt.stats.onFollow(rows.customerId)
        } else {
          this.$dt.stats.onCustomer(rows.customerId)
        }
        this.detailsFlag = true
        this.detailsParams = {
          hasAttention: true,
          customerId: rows.customerId,
          userCustomerId: rows.userCustomerId,
          buildingId: this.buildingId,
          userId: rows.userId,
          cityCode: this.buildMess.cityId
        }
        if (isFollow) {
          this.detailsParams.isFollow = isFollow
        }
      },
      initData(reset = false) {
        this.$refs.allCustomer.fetch(reset)
      }
    },
    async mounted() {
      await this.getCustomerHeadList()
      // customerOptMgr.getConsultant()
      // clueCustomerMgr.selectTeamUser()
      customerOptMgr.getFilterOptions()
      customerOptMgr.getChannel()
      customerOptMgr.getArea()
      this.$refs.allCustomer.init(this)
      this.$refs.allCustomer.fetch()
      // this.getCountData()
    }
  }
</script>
<style lang="scss" scoped>
  .popClass {
    display: none !important;
  }

  .allCustomersManagement {
    padding: 20px;

    .newArticleStyle {
      margin-bottom: 20px;
      overflow: hidden;

      .imprt {
        line-height: 32px;
        float: right;
        display: flex;
        flex-direction: row;

        > * {
          margin-right: 5px;
        }

        .impotBtn {
          line-height: 2;
          cursor: pointer;
          color: #2d8cf0;
          text-align: center;

          &:first-child {
            border-bottom: 1px #e8eaec solid;
          }
        }
      }
    }
  }

  .transferFooter {
    margin-top: 20px;
    display: flex;
    flex-direction: row;
    justify-content: center;

    button {
      width: 80px;
      margin: 0 10px;
    }
  }

  .detailsCon {
    height: 80vh;
    overflow-y: auto;
  }

  ::v-deep .c_Feature .ivu-poptip {
    width: 100%;

    .ivu-poptip-rel {
      width: 100%;
    }

    .featureZ {
      cursor: pointer;
      height: 80px;
      overflow: hidden;
      white-space: nowrap;
      text-overflow: ellipsis;
      line-height: 80px;
    }
  }
</style>

<style>
  .N_poptip .ivu-poptip-inner {
    background: rgba(235, 247, 255, 1) !important;
    white-space: normal;
  }

  .ivu-spin-fix {
    background-color: rgba(255, 255, 255, 0.35);
    width: calc(100% - 200px);
    left: 200px;
  }

  .demo-spin-icon-load {
    animation: ani-demo-spin 1s linear infinite;
  }

  @keyframes ani-demo-spin {
    from {
      transform: rotate(0deg);
    }

    50% {
      transform: rotate(180deg);
    }

    to {
      transform: rotate(360deg);
    }
  }
</style>
